package com.example.vpn_demo.packet

import android.util.Log
import com.example.vpn_demo.model.HttpRequest
import java.nio.charset.Charset

object ProtocolParser {
    private const val TAG = "ProtocolParser"
    
    fun parseHttpRequest(packet: NetworkPacket): HttpRequest? {
        try {
            val content = String(packet.data, Charset.forName("UTF-8"))
            if (!content.contains("HTTP")) return null
            
            val lines = content.split("\r\n")
            val firstLine = lines.firstOrNull()?.split(" ") ?: return null
            
            if (firstLine.size != 3) return null
            
            val method = firstLine[0]
            val path = firstLine[1]
            val protocol = firstLine[2]
            
            // 解析headers
            val headers = mutableMapOf<String, String>()
            var host = ""
            
            for (line in lines.drop(1)) {
                if (line.isEmpty()) break
                val headerParts = line.split(": ", limit = 2)
                if (headerParts.size == 2) {
                    val (key, value) = headerParts
                    headers[key] = value
                    if (key.equals("Host", ignoreCase = true)) {
                        host = value
                    }
                }
            }
            
            return HttpRequest(
                method = method,
                url = "http://$host$path",
                host = host,
                path = path,
                protocol = protocol,
                requestHeaders = headers,
                sourceIp = packet.sourceIp,
                sourcePort = packet.sourcePort,
                destIp = packet.destIp,
                destPort = packet.destPort
            )
        } catch (e: Exception) {
            Log.e(TAG, "Error parsing HTTP request", e)
            return null
        }
    }
    
    fun isProtobuf(packet: NetworkPacket): Boolean {
        // 检查Content-Type header或其他特征来识别protobuf
        val content = String(packet.data, Charset.forName("UTF-8"))
        return content.contains("application/x-protobuf") ||
               content.contains("application/protobuf") ||
               hasProtobufSignature(packet.data)
    }
    
    private fun hasProtobufSignature(data: ByteArray): Boolean {
        // 实现protobuf数据的特征检测
        // 这需要根据你的具体protobuf消息格式来实现
        return false
    }
} 